package service

import (
	"context"
	"errors"
	"gitee.com/ZLX0326/gin_learn/bingweb/internal/domain"
	"gitee.com/ZLX0326/gin_learn/bingweb/internal/repo"
	"golang.org/x/crypto/bcrypt"
)

var (
	UserNotFondError    = repo.UserNotFoundErr
	PasswordFailedError = errors.New("用户名或密码错误")
)

type UserService struct {
	Repo *repo.UserRepo
}

func (svc *UserService) SingUp(ctx context.Context, u domain.User) error {
	password, err := bcrypt.GenerateFromPassword([]byte(u.Passwd), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Passwd = string(password)
	err = svc.Repo.Create(ctx, u)
	if err != nil {
		return err
	}
	return nil
}

func (svc *UserService) Login(ctx context.Context, email, password string) (*domain.User, error) {
	u, err := svc.Repo.FindByEmail(ctx, email)
	if errors.Is(err, UserNotFondError) {
		return u, PasswordFailedError
	}
	if err != nil {
		return u, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(u.Passwd), []byte(password))
	if err != nil {
		return u, PasswordFailedError
	}
	return u, nil

}
